﻿using Microsoft.AspNetCore.Http;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lg.Core.FileHelper
{
    public class Excel
    {
        public string? FilePath { get; set; }
        public IWorkbook? Workbook { get; set; }
        /// <summary>
        /// excel文件存的相对路径
        /// </summary>
        /// <param name="filename"></param>
        public Excel(string? relativePath = null)
        {
            if (relativePath != null)
            {
                FilePath = AppContext.BaseDirectory + relativePath.Replace("/", "\\");
                if (File.Exists(FilePath))
                {
                    using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
                    {
                        //根据文件类型初始化对应的工作部对像
                        if (FilePath.IndexOf(".xlsx") > 0)
                            Workbook = new XSSFWorkbook(fs);
                        else if (FilePath.IndexOf(".xls") > 0)
                            Workbook = new HSSFWorkbook(fs);
                        else
                            throw new Exception("Wrong file ext!");
                    }
                }
                else
                {
                    throw new Exception("文件不存在!");
                }
            }

        }

        /// <summary>
        /// 通过上传的文件对像FormFile构造Excel类，实例并赋值Workbook对像
        /// </summary>
        /// <param name="file"></param>
        /// <exception cref="Exception"></exception>
        public Excel(IFormFile file) 
        {
            using (Stream fs = file.OpenReadStream())
            {
                //根据文件类型初始化对应的工作部对像
                if (file.FileName.IndexOf(".xlsx") > 0)
                    Workbook = new XSSFWorkbook(fs);
                else if (file.FileName.IndexOf(".xls") > 0)
                    Workbook = new HSSFWorkbook(fs);
                else
                    throw new Exception("Wrong file ext!");
            }
        }
    }
}
